﻿/* Copyright (c) 2010 Lexalytics Inc.

 Permission is hereby granted, free of charge, to any person
 obtaining a copy of this software and associated documentation
 files (the "Software"), to deal in the Software without
 restriction, including without limitation the rights to use,
 copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following
 conditions:

 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace Lexalytics4Excel.Dialogs
{
    /// <summary>
    /// Dialog displayed the first time a user selects data for analysis. Gathers the information needed to 
    /// create a new Lexascope project for the data.
    /// </summary>
    public partial class NewProject : Form
    {
        // Private data members
        private Profiles _Profiles = new Profiles();
        private string _SelectedProfile = "";
        private string _ProjectName = "";

        /// <summary>
        /// Property to capture user specification of profile to use
        /// </summary>
        public string SelectedProfile
        {
            get { return ProfileSelector.SelectedValue.ToString(); }
        }

        /// <summary>
        /// Property to capture user specification of project name
        /// </summary>
        public string ProjectName
        {
            get { return _ProjectName; }
        }

        /// <summary>
        /// Dialog constructor
        /// </summary>
        /// <param name="ProfileCollection">Collection class of profiles to select from for project creation</param>
        /// <param name="CurrentProfile">Current profile selected for project, if exists</param>
        public NewProject(Profiles ProfileCollection, string CurrentProfile)
        {
            InitializeComponent();
            _Profiles = ProfileCollection;
            _SelectedProfile = CurrentProfile;
            _ProjectName = System.Guid.NewGuid().ToString();
            OkButton.Enabled = false;
        }

        /// <summary>
        /// Event handler for dialog load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NewProject_Load(object sender, EventArgs e)
        {
            try
            {
                // Set up contents of profile selection dropdown, default if already selected
                ProfileSelector.DataSource = _Profiles.ProfileNames;
                if (!String.IsNullOrEmpty(_SelectedProfile))
                {
                    ProfileSelector.SelectedItem = ProfileSelector.Items[ProfileSelector.Items.IndexOf(_SelectedProfile)];
                    ProfileSelectDescription.Enabled = false;
                    ProfileSelector.Enabled = false;
                }
                // If there is at least one profile, enable to OK button.
                if (_Profiles.Count>=1)
                    OkButton.Enabled = true;
            }
            catch (Exception err)
            {
                MessageBox.Show("There was a problem determining the profiles that can be used.\n" + err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }
        }

        /// <summary>
        /// Event handler for OK button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OkButton_Click(object sender, EventArgs e)
        {
            #region Commented out in shift from web service to local operation
/*            try
            {
                if (ProjectNameText.Text.Length > 0)
                {
                    if (!ProjectExists(ProjectNameText.Text, SelectedProfile))
                    {
                        DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        NewProjectValidation.SetError(ProjectNameText, "A project by this name already exists for this profile");
                    }
                }
                else
                {
                    NewProjectValidation.SetError(ProjectNameText, "A project name is needed");
                }
            }
            catch (Exception err)
            {
                MessageBox.Show("There was a problem contacting the web service to confirm the project name.\n" + err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                DialogResult = DialogResult.Cancel;
                this.Close();
            }
 */ 
            #endregion 

            DialogResult = DialogResult.OK;
            this.Close();
            return;
        }

        #region Commented out in shift from web service to local operation
/*        
        /// <summary>
        /// Enable the OK button only if a project name has been specified and profile selected
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProjectNameText_TextChanged(object sender, EventArgs e)
        {
            if (ProjectNameText.Text.Length > 0)
            {
               NewProjectValidation.SetError(ProjectNameText, "");
                OkButton.Enabled = true;
            }
        }

        private void ProjectNameText_Validating(object sender, CancelEventArgs e)
        {
            try
            {
                if (CheckProjectName(ProjectNameText.Text))
                {
                    NewProjectValidation.SetError(ProjectNameText, "");
                }
                else
                {
                   NewProjectValidation.SetError(ProjectNameText, "Invalid characters detected in the project name specified.");
                    e.Cancel = true;
                }
            }
            catch (Exception err)
            {
                NewProjectValidation.SetError(ProjectNameText, err.Message);
                e.Cancel = true;
            }
        }

        /// <summary>
        /// Method to perform any and all validation of project name
        /// </summary>
        /// <param name="projectName">Project name input from user</param>
        /// <returns>Boolean indication of valid project name in terms of length and content</returns>
        private bool CheckProjectName(string projectName)
        {
            bool bRet = false;
            if (!String.IsNullOrEmpty(projectName))
            {
                // Check that it is a valid key structure
                Regex regKey = new Regex(@"(\w(\s)?)+", RegexOptions.None);
                if (regKey.IsMatch(projectName))
                {
                    bRet = true;
                }
            }

            return bRet;
        }

        /// <summary>
        /// Method to determine if the provided project name already exists under the selected profile
        /// </summary>
        /// <param name="projectName">Project name specified by user</param>
        /// <param name="profileName">Profile selected by user for project</param>
        /// <returns>Boolean indicating if a project of the specified name already exists for the profile</returns>
        private bool ProjectExists(string projectName, string profileName)
        {
            bool bRet = false;

            List<string> projectList = new List<string>();
            Profile myProfile = _Profiles[profileName];
            LXAWebService wsLXA = new LXAWebService();
            int nRet = wsLXA.WSGetProjectList(myProfile.ServiceURL, myProfile.PublicKey, myProfile.PrivateKey, ref projectList);
            bRet = projectList.Contains(projectName);
            return bRet;
        }
*/
        #endregion
    }
}
